package com.tian.print.http;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;


import com.tian.print.app.AppConfig;
import com.tian.print.http.response.Response;
import com.tian.print.utils.DateUtils;
import com.tian.print.utils.NetWorkUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Description: 用于网络访问的 观察者对象拥有对数据的解析 有别于<linked {@link NormalObserver}
 * Author：skyTian <p>
 * Time:2017/11/3 09:47
 * CopyRight:com,sky
 * <p>
 * <br> note 2018-01-31 :
 */
public abstract class BaseObserver<T> implements Observer<Response> {
    private LoadingDialog loadingDialog;
    private Context context;

    public BaseObserver() {
    }

    public BaseObserver(Context context) {
        this.context = context;
        if (context != null && context instanceof Activity)
            this.loadingDialog = LoadingDialog.newInstance(null);
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        if (context != null) {
            //对于网络的检查,在没有网络的时候,调用onFailed方法,并且切断与上游的联系
            if (!NetWorkUtils.isNetworkConnected(context.getApplicationContext())) {
                Toast.makeText(context.getApplicationContext(), "网络出现问题", Toast.LENGTH_SHORT).show();
                onFailure(AppConfig.NO_NETWORK);
                d.dispose();
                return;
            }

            if (context instanceof Activity)
                loadingDialog.show(context);
        }
    }


    @Override
    public void onNext(@NonNull Response bb) {
        if (loadingDialog != null)
            loadingDialog.dismiss();

        if (bb.getCode() == 1) {
            T t = (T) bb.getData();
            onSuccess(t);
        }
        //
        else {
            String msg = bb.getMsg();
            onFailure(msg);
        }

    }

    @Override
    public void onError(@NonNull Throwable e) {
        Log.i("request_error", DateUtils.getCurrentTime() + " " + e.getMessage());
        if (loadingDialog != null)
            loadingDialog.dismiss();

        if (context != null && !(e instanceof ConnectException) && !(e instanceof SocketTimeoutException))
            Toast.makeText(context.getApplicationContext(), DateUtils.getCurrentTime() + " " + e.getMessage(), Toast.LENGTH_LONG).show();

        onFailure(AppConfig.NO_NETWORK);
    }

    @Override
    public void onComplete() {
    }

    public abstract void onSuccess(T t);

    public abstract void onFailure(String msg);
}
